package com.moonshineproject.plugin.console.view
{
	import com.moonshineproject.plugin.console.ConsoleCommandEvent;
	import com.moonshineproject.text.TextEditor;
	import com.moonshineproject.text.TextLineModel;
	import com.moonshineproject.text.change.*;
	import com.moonshineproject.text.events.ChangeEvent;
	
	import mx.utils.StringUtil;
	
	public class CommandLineEditor extends TextEditor
	{
		private var history:Array = [];
		
		public function CommandLineEditor()
		{
			super(false);
			this.addEventListener(ChangeEvent.TEXT_CHANGE, handleChange);
		}
		
		private function handleChange(event:ChangeEvent):void
		{
			var change:TextChangeBase = event.change;
			
			if (change is TextChangeInsert) applyChangeInsert(TextChangeInsert(change));
			else if (change is TextChangeMulti) applyChangeMulti(TextChangeMulti(change));
		}
		
		private function applyChangeMulti(change:TextChangeMulti):void
		{
			for each (var subchange:TextChangeBase in change.changes)
			{
				if (subchange is TextChangeInsert) applyChangeInsert(TextChangeInsert(subchange));
			}
		}
		
		private function applyChangeInsert(change:TextChangeInsert):void
		{
			if (model.lines.length > 1)
			{
				for (var i:int = 0; i < model.lines.length-1; i++)
				{
					var m:TextLineModel = model.lines[i];
					history.push(m.text);
					exec(m.text);					
				}
				
				dataProvider = "";
			}
		}
		
		private function exec(line:String):void
		{
			line = StringUtil.trim(line);
			if (line == "") return;
			
			var split:Array = line.split(' ');
			var c:String = split[0];
			var args:Array = split.splice(1);
			
			dispatchEvent( new ConsoleCommandEvent(c, args) );
		}
	}
}